package com.pangu;

import com.pangu.bean.ModuleConfig;
import com.pangu.util.ModuleConfigJsonParser;

import org.json.JSONObject;

import android.content.res.AssetManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * 预配置管理器
 * <p/>
 * Created by cxlin
 */
public class PreConfigManager {

    public static final String TAG = PreConfigManager.class.getSimpleName();
    // 模块配置信息
    private ArrayList<ModuleConfig> moduleConfigList;

    private AMApplication imContext;

    public PreConfigManager(AMApplication imContext) {
        this.imContext = imContext;
    }

    /**
     * 获取模块的配置信息
     *
     * @return
     */
    public ArrayList<ModuleConfig> getModuleConfigList() {
        if (moduleConfigList == null) {
            String modulesJsonFileName = imContext.getModulesConfigName();
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader bf = null;
            try {
                AssetManager assetManager = imContext.getAssets();
                bf = new BufferedReader(new InputStreamReader(assetManager.open(modulesJsonFileName)));
                String line = null;
                while ((line = bf.readLine()) != null) {
                    stringBuilder.append(line);
                }

                JSONObject moduleConfigObject = new JSONObject(stringBuilder.toString());

                ModuleConfigJsonParser moduleConfigJsonParser = new ModuleConfigJsonParser();
                moduleConfigJsonParser.parserJson(moduleConfigObject);
                moduleConfigList = moduleConfigJsonParser.getModuleConfigList();

            } catch (Exception e) {
                e.printStackTrace();

            } finally {
                if (bf != null) {
                    try {
                        bf.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        return moduleConfigList;
    }

}
